#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <unistd.h>

#define path "/home/liusong"
#define proj 0x666
#define desize 4096

key_t GetshmkeyorDie()
{
    key_t key = ftok(path,proj);
    if(key < 0)
    {
        std::cout<<"ftok error: "<<errno<<" stringerror: "<<strerror(errno)<<std::endl;
        exit(1);
    }
    return key;
}


int CreatshmorDie(key_t key,int size,int flag)
{
    int shmid = shmget(key,size,flag);
    if(shmid < 0)
    {
        std::cout<<"Creatshm error: "<<errno<<" stringerror: "<<strerror(errno)<<std::endl;
        exit(2);
    }
    return shmid;
}

int Creatshm(key_t key,int size)
{
    return CreatshmorDie(key,size,IPC_CREAT | IPC_EXCL | 0666);

}

int Getshm(key_t key,int size)
{
    return CreatshmorDie(key,size,IPC_CREAT);
}


void Deleteshm(int shmid)
{
    int n = shmctl(shmid,IPC_RMID,nullptr);
    if(n < 0)
    {
        std::cout<<"Deleteshm error: "<<errno<<" stringerror: "<<strerror(errno)<<std::endl;
    }
    std::cout<<"Deleteshm Success "<<std::endl;
}



void* AddshmTouch(int shmid)
{
    void* addr = shmat(shmid,nullptr,0);
    if((long long int)addr < 0)
    {
        std::cout<<"AddshmTouch error: "<<errno<<" stringerror: "<<strerror(errno)<<std::endl;
        return nullptr;
    }
    return addr;
}


void DeshmTouch(void* addr)
{
    int n = shmdt(addr);
    if(n < 0)
    {
        std::cout<<"DeshmTouch error: "<<errno<<" stringerror: "<<strerror(errno)<<std::endl;
    }
}